<template>
  <div class="page-wrapper">
    <div class="page-tab">
      <template v-if="historyStack.length">
        <div
          class="tab-item"
          :class="curRouteName === item.name ? 'active' : ''"
          v-for="(item, index) in historyStack"
          :key="item.name as unknown as string"
          @click="onTabClick(item.name as unknown as string)"
          @contextmenu.prevent="($event) => onContextMenu($event, item.name)"
        >
          <span>{{ item.meta.title }}</span>
          <CloseOutlined
            class="close-icon"
            @click.stop="onCloseTab(item.name as unknown as string)"
            v-if="!(index === 0 && historyStack.length === 1)"
          />
        </div>
      </template>
    </div>
  </div>
</template>
<script setup lang="ts">
import { CloseOutlined } from '@ant-design/icons-vue'
import { computed, nextTick, onMounted, ref, type UnwrapRef, watch } from 'vue'
import BScroll from '@better-scroll/core'
import _ from 'lodash'
import { type RouteLocationNormalizedLoaded, useRoute, useRouter } from 'vue-router'
import { useSettings } from '@/stores/settings'
import ContextMenu from '@imengyu/vue3-context-menu'
const router = useRouter()
const route = useRoute()
const historyStack = ref<RouteLocationNormalizedLoaded[]>([])

watch(
  () => route.name,
  (val) => {
    const flag = historyStack.value.find((item) => {
      return item.name === val
    })
    if (!flag) {
      historyStack.value.push(_.cloneDeep(route))
    }
  },
  { immediate: true }
)

// 当前激活路由
const curRouteName = computed(() => {
  return route.name
})

// 关闭tab
const onCloseTab = (name: string) => {
  // 栈深度变化之前
  if (historyStack.value.length === 1) {
    return
  }
  historyStack.value = historyStack.value.filter((item) => {
    return item.name !== name
  })

  // 栈深度变化之后
  if (historyStack.value.length !== 1) {
    if (name === curRouteName.value) {
      onTabClick(historyStack.value[0].name)
    }
  } else {
    onTabClick(historyStack.value[0].name)
  }
}

// 点击tab
const onTabClick = (name: UnwrapRef<RouteLocationNormalizedLoaded['name']>) => {
  router
    .push({ name: name as string })
    .then((r) => {
      // pass
    })
    .catch((error) => {
      console.error('Failed to navigate to tab:', error)
    })
}

const settingsStore = useSettings()

// 刷新当前页面
const onRefreshCurPage = () => {
  settingsStore.$patch({
    isReload: false
  })
  setTimeout(() => {
    settingsStore.$patch({
      isReload: true
    })
  }, 200)
}

function onContextMenu(e: MouseEvent, key?: UnwrapRef<RouteLocationNormalizedLoaded['name']>) {
  //prevent the browser's default menu
  e.preventDefault()
  const curIndex = historyStack.value.findIndex((item) => item.name === key)
  const totalLen = historyStack.value.length

  //show your menu
  ContextMenu.showContextMenu({
    x: e.x,
    y: e.y,
    items: [
      {
        label: '关闭',
        onClick: () => {
          onCloseTab(key as string)
        },
        disabled: historyStack.value.length === 1
      },
      {
        label: '关闭其他',
        onClick: () => {
          historyStack.value = historyStack.value.filter((item) => item.name === key)
        },
        disabled: historyStack.value.length === 1
      },
      {
        label: '关闭右侧',
        onClick: () => {
          historyStack.value = historyStack.value.slice(0, curIndex + 1)
        },
        disabled: historyStack.value.length === 1 || curIndex === totalLen - 1
      },
      {
        label: '关闭左侧',
        onClick: () => {
          historyStack.value = historyStack.value.slice(curIndex)
        },
        disabled: historyStack.value.length === 1 || curIndex === 0
      }
    ]
  })
}
const bs = ref<any>()
onMounted(() => {
  init()
})
function init() {
  bs.value = new BScroll('.page-wrapper', {
    scrollX: true
  })
}
watch(
  () => historyStack,
  () => {
    nextTick(() => {
      bs.value.refresh()
    })
  },
  { deep: true }
)
defineExpose({
  onRefreshCurPage
})
</script>
<style scoped lang="scss">
.page-wrapper {
  position: relative;
  height: 100%;
  width: 100%;
  white-space: nowrap;
  overflow: hidden;
}

.page-tab {
  padding-top: 10px;
  height: 100%;
  display: inline-block;

  .tab-item {
    user-select: none;
    padding: 8px 12px 0;
    color: rgb(31, 31, 31);
    cursor: pointer;
    position: relative;
    flex-shrink: 0;
    display: inline-block;
    height: 100%;
    vertical-align: middle;
    border-top-left-radius: 8px;
    border-top-right-radius: 8px;
    transition: all 0.5s;
    .close-icon {
      font-size: 12px;
      cursor: pointer;
      position: relative;
      margin-left: 8px;
      margin-top: 3px;
      z-index: 1;
      padding: 2px;
    }
    &:not(.active) .close-icon:hover {
      color: #eee;
      background-color: #999999;
      border-radius: 50%;
    }
    &:hover {
      background-color: #dee1e6;
    }
    &.active {
      color: rgb(100, 108, 255);
      background-color: #f0f0ff;
    }
    &.active .close-icon:hover {
      color: #ffffff;
      background-color: rgb(100, 108, 255);
      border-radius: 50%;
    }
  }
}
</style>
